package com.studio49.exmple.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.studio49.exmple.entity.web.sys.User;
import com.studio49.exmple.entity.web.sys.bo.SessionUserBo;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import com.studio49.exmple.common.constant.SysConstant;

/**
 * 项目通用工具类
 * @author chensj
 * @date 2019年4月17日  上午10:34:50
 * @version 1.0
 */
public abstract class PubUtils {

	private static final Logger logger = LogManager.getLogger(PubUtils.class);

	/**
	 * 
	 * 获取富文本内容中的图片地址
	 * 
	 */
	public static List<String> findImg(String context, int size) {

		List<String> list = null;
		try {
			list = new ArrayList<String>();
			String regex = " src=&quot;(.*?)&quot;";
			Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
			Matcher ma = pa.matcher(context);
			String tmp = "";
			int index = 1;
			while (ma.find()) {
				if (index <= size) {
					tmp = ma.group().replace("&quot;", "\"")
							.replace("&quot;", "\"");
					list.add(tmp);
					index++;
				}
			}
		} catch (Exception e) {
			logger.error("findImg failed!", e);
		}
		return list;
	}

	/**
	 * 
	 * 判断是否全为数字
	 * 
	 */
	public static boolean isNumber(String number) {
		if (number == null)
			return false;
		return number.matches("[+-]?[1-9]+[0-9]*(\\.[0-9]+)?");
	}

	/**
	 * 
	 * 字符非空验证
	 * 
	 */
	public static boolean isEmpty(String str) {
		if (null == str) {
			return true;
		} else if ("".equalsIgnoreCase(str.trim())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 
	 * 获取session用户对象
	 *
	 */
	public static User getSessionUser(HttpServletRequest request)
			throws Exception {
		HttpSession session = request.getSession();
		User user = (User) session
				.getAttribute(SysConstant.CURRENT_USER_OBJECT);
		return user;
	}
	
	/**
	 * 获取session用户菜单封装对象
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static SessionUserBo getSessionUserBo(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		SessionUserBo user = (SessionUserBo) session.getAttribute(SysConstant.CURRENT_USER_OBJECT);
		return user;
	}

	/**
	 * 
	 * 获得客户端真实IP地址
	 * 
	 */
	public static String getRemoteHost(
			javax.servlet.http.HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}

	/**
	 * 
	 * 判断服务器是否是Windows
	 * 
	 */
	public static boolean isWindowsOS() {
		boolean isWindowsOS = false;
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().indexOf("windows") > -1) {
			isWindowsOS = true;
		}
		return isWindowsOS;
	}

	/**
	 * 获取本机ip地址，并自动区分Windows还是linux操作系统
	 * 
	 */
	public static String getLocalIP() {
		String sIP = "";
		InetAddress ip = null;
		try {
			if (isWindowsOS()) {
				ip = InetAddress.getLocalHost();
			} else {
				boolean bFindIP = false;
				Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
						.getNetworkInterfaces();
				while (netInterfaces.hasMoreElements()) {
					if (bFindIP) {
						break;
					}
					NetworkInterface ni = (NetworkInterface) netInterfaces
							.nextElement();
					// 遍历所有ip
					Enumeration<InetAddress> ips = ni.getInetAddresses();
					while (ips.hasMoreElements()) {
						ip = (InetAddress) ips.nextElement();
						if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
								&& ip.getHostAddress().indexOf(":") == -1) {
							bFindIP = true;
							break;
						}
					}
				}
			}
			if (null != ip) {
				sIP = ip.getHostAddress();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sIP;
	}

	/**
	 * 判断当前服务器IP是否与配置的IP一致
	 * 
	 * @param task
	 * @return
	 */
	public static boolean checkIp(String ipString) {
		if (StringUtils.isEmpty(ipString))
			return true;
		String[] ips = ipString.split(",");
		String localIp = getLocalIP();
		for (String ip : ips) {
			if (localIp.equals(ip)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 
	 * 把list转换为一个用split分隔的字符串
	 * 
	 */
	@SuppressWarnings("rawtypes")
	public static String listToString(List list, String split) {
		StringBuilder sb = new StringBuilder();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				if (i < list.size() - 1) {
					sb.append(list.get(i) + split);
				} else {
					sb.append(list.get(i));
				}
			}
		}
		return sb.toString();
	}
	/**
	 * 返回一个合适的文件大小
	 * @param fileSize
	 * @return
	 */
	public static String calculateFileSize(String fileSize){
		String result = "";
		Long lfileSize = Long.valueOf(fileSize);
		lfileSize = lfileSize/1024;
		if(lfileSize < 1024){
			result = lfileSize.toString() + "KB";
			return result;
		}else{
			lfileSize = lfileSize/1024;
			if(lfileSize < 1024){
				result = lfileSize.toString() + "MB";
				return result;
			}else{
				lfileSize = lfileSize/1024;
				if(lfileSize < 1024){
					result = lfileSize.toString() + "GB";
					return result;
				}else{
					lfileSize = lfileSize/1024;
					if(lfileSize < 1024){
						result = lfileSize.toString() + "TB";
						return result;
					}
				}
			}
		}
		return result;
	}

//	public static void main(String[] args) {
//		String content = "s地方&lt;img src=&quot;http://localhost:8080/OCEDU/admin/ocedu/plug-in/ueditor/jsp/upload1/20160816/59081471322656529.png&quot; title=&quot;描述&quot; _src=&quot;http://localhost:8080/OCEDU/admin/ocedu/plug-in/ueditor/jsp/upload1/20160816/59081471322656529.png&quot;&gt;水电费&lt;img src=&quot;http://localhost:8080/OCEDU/admin/ocedu/plug-in/ueditor/jsp/upload1/20160816/91581471322667251.png&quot; title=&quot;QQ截图20160808110118.png&quot; _src=&quot;http://localhost:8080/OCEDU/admin/ocedu/plug-in/ueditor/jsp/upload1/20160816/91581471322667251.png&quot;&gt;";
//		List<String> imgList = PubUtils.findImg(content, 3);
//		System.out.println(imgList.size());
//		for (String img : imgList) {
//			System.out.println(img);
//		}
//	}
	
	public static String removeHtmlTag(String content) {
		content=StringEscapeUtils.unescapeXml(content);
        Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>");
        Matcher m = p.matcher(content);
        if (m.find()) {
            content = content.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
            content = removeHtmlTag(content);//递归删除
        }
        return content;
    }

	/**
	 * 实体类转map
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();

       List<Field> fieldList = new ArrayList<>() ;
        Class<?> tempClass = obj.getClass();
        while (tempClass != null) {//当父类为null的时候说明到达了最上层的父类(Object类).
              fieldList.addAll(Arrays.asList(tempClass .getDeclaredFields()));
              tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己
        }
        for (Field field : fieldList) {
            field.setAccessible(true);
            Object val = field.get(obj);
            if(val != null) {
            	map.put(field.getName(), val);
            }
        }
        return map;
    }
	/**
	 * map转实体类
	 * @param map
	 * @param beanClass
	 * @return
	 * @throws Exception
	 */
	public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) throws Exception {
        if (map == null)
            return null;

        T obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }

            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }
        return obj;
    }

	/**
	 * 检验str是否在orgStr中
	 * @param orgStr			目标字段,以逗号隔开
	 * @param str				检验字段
	 * @return
	 * @throws Exception
	 */
	public static boolean isStrIn(String orgStr, String str) {
       String[] strArr = orgStr.split(",");
       int result = Arrays.binarySearch(strArr, str); //在数组中搜索是否含有5
       boolean exist = true;
       if(result < 0) {
    	   exist = false;
       }
        return exist;
    }

//	public static void main(String[] args) {
//		System.out.println(isStrIn("1,2,5,7d", "5"));
//	}
	
}
